<template>
  <SplitLayout :leftWidth="'120px'">
    <div slot="left" class="left">
      <a-menu @select="onSelect" :selectedKeys="selectedKeys">
        <a-menu-item v-if="isAdd || category == 1" :key="1">区域告警</a-menu-item>
        <a-menu-item v-if="isAdd || category == 2" :key="2">物品告警</a-menu-item>
        <a-menu-item v-if="isAdd || category == 3" :key="3">账户告警</a-menu-item>
        <a-menu-item v-if="isAdd || category == 4" :key="4">网站告警</a-menu-item>
      </a-menu>
    </div>
    <div slot="top" class="header-top" v-if="category != 1">
      <TargetList v-if="category != 1" ref="targetListId" />
      <ImportModal ref="importModalId" @importData="onImportData" />
    </div>
    <div class="con-content">
      <a-form-model
        :label-col="{ span: 2 }"
        :wrapper-col="{ span: 12 }"
        ref="ruleForm"
        :model="formData"
        :rules="validatorRules"
      >
        <a-form-model-item label="告警任务" prop="name">
          <a-input v-model="formData.name" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item label="告警区域" v-if="category == 1" prop="alarmArea">
          <a-select placeholder="请选择" mode="multiple" v-model="formData.alarmArea">
            <a-select-option v-for="(item, index) in areaData1" :key="index" :value="item.name">{{
              item.name
            }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="告警时间范围" prop="rangePickerTime">
          <a-range-picker
            :allowClear="true"
            v-model="formData.rangePickerTime"
            valueFormat="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD HH:mm:ss"
            showTime
            @change="rangePickerChange"
            style="width: 100%"
          />
        </a-form-model-item>
        <a-form-model-item label="通信方式" v-if="category == 3" class="yczh">
          <AddLabel ref="addLabelId1" class="labelBox" placeholderText="请输入手机号，微信号，QQ号，然后回车" />
          <!-- <a-tooltip class="toolTip" placement="rightBottom" :overlayStyle="{ minWidth: `120px`, maxWidth: `400px` }">
            <template slot="title">
              <div style="padding-bottom: 5px">
                通信方式可多个输入，当点击回车时，便结束当前一个输入、在次输入代表新一个条件
              </div>
            </template>
            <a-icon category="question-circle" />
          </a-tooltip> -->
        </a-form-model-item>
        <a-form-model-item label="异常账户" v-if="category == 2" class="yczh">
          <AddLabel ref="addLabelId2" class="labelBox" />
          <span class="zjBtn">
            <a-button style="margin-right: 20px" @click="onInportYCZH"> 增加 </a-button>
            <a-tooltip class="tp" placement="rightBottom" :overlayStyle="{ minWidth: `120px`, maxWidth: `400px` }">
              <template slot="title">
                <div style="padding-bottom: 5px">最多可导入100个异常账号</div>
              </template>
              <a-icon type="question-circle" />
            </a-tooltip>
          </span>
        </a-form-model-item>
        <a-form-model-item label="特定区域" class="tdqy" v-if="category == 1">
          <a-select placeholder="机场区域" mode="multiple" v-model="formData.areaData2">
            <a-select-option v-for="(item, index) in areaData2" :key="index" :value="item.name">{{
              item.name
            }}</a-select-option>
          </a-select>
          <a-select placeholder="火车站区域" mode="multiple" v-model="formData.areaData3" style="margin: 0 2%">
            <a-select-option v-for="(item, index) in areaData3" :key="index" :value="item.name">{{
              item.name
            }}</a-select-option>
          </a-select>
          <a-select placeholder="港口区域" mode="multiple" v-model="formData.areaData4">
            <a-select-option v-for="(item, index) in areaData4" :key="index" :value="item.name">{{
              item.name
            }}</a-select-option>
          </a-select>
          <a-tooltip class="toolTip" placement="rightBottom" :overlayStyle="{ minWidth: `120px`, maxWidth: `400px` }">
            <template slot="title">
              <div style="padding-bottom: 5px">最多可选择10个特定区域</div>
            </template>
            <a-icon type="question-circle" />
          </a-tooltip>
        </a-form-model-item>
        <a-form-model-item label="发布时间" v-if="category == 2 || category == 3" class="fbsj">
          <span>异常账户发布时间在 </span>
          <a-date-picker
            :allowClear="true"
            placeholder="请选择"
            v-model="formData.abnormalAccountRelease"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
            style="width: 15%"
          />
          前
          <a-input-number v-model="formData.dayQ" style="width: 10%" placeholder="" />
          <span> 天，后 </span>
          <a-input-number v-model="formData.dayH" style="width: 10%" placeholder="" />
          <span> 天，发布疑似走私商品。</span>
        </a-form-model-item>
        <a-form-model-item label="关键词" prop="keywordArr">
          <a-select placeholder="请选择" mode="multiple" v-model="formData.keywordArr">
            <a-select-option v-for="(item, index) in keywordData" :key="index" :value="item.name">{{
              item.name
            }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="数据来源" v-if="category != 4" class="zdy-form-item-label" prop="dataSource">
          <a-checkbox :indeterminate="indeterminateState" :checked="checkAllState" @change="onCheckAllChange($event)">
            全部
          </a-checkbox>
          <j-multi-select-tag
            v-model="formData.dataSource"
            dictCode="dataSource"
            type="checkbox"
            @change="onChange($event)"
          />
        </a-form-model-item>
        <a-form-model-item label="推送告警条数" v-if="category == 4" class="fbsj">
          <span> 每日可推送告警数 </span>
          <a-input-number v-model="formData.num" style="width: 10%" placeholder="" />
          <span> 条 </span>
          <a-tooltip placement="rightBottom" :overlayStyle="{ minWidth: `120px`, maxWidth: `400px` }">
            <template slot="title">
              <div style="padding-bottom: 5px">根据设定告警条数进行推送，不设定条数时符合触发条件的情报进行推送</div>
            </template>
            <a-icon type="question-circle" />
          </a-tooltip>
        </a-form-model-item>
        <div style="margin-top: 20px">
          <a-form-model-item :wrapper-col="{ offset: 0 }" style="margin-bottom: 0">
            <a-button @click="onBack"> 取消 </a-button>
            <a-button style="margin-left: 10px" type="primary" @click="onSubmit"> 确定 </a-button>
          </a-form-model-item>
        </div>
      </a-form-model>
    </div>
  </SplitLayout>
</template>
<script>
import { SplitLayout } from '@/components/zxd/layouts'
import TargetList from './components/targetList'
import ImportModal from './components/ImportModal'
import AddLabel from './components/AddLabel'
import { getXzqhList, getDictItemsFromCache } from '@/api/api'
import * as alarmApi from '@/api/alarm.js'
import moment from 'moment'
export default {
  components: {
    SplitLayout,
    TargetList,
    ImportModal,
    AddLabel,
  },
  data() {
    return {
      moment,
      loading: false,
      id: this.$route.query.id,
      category: this.$route.query.category,
      rangeTime: undefined,
      formData: {
        //公用
        name: '',
        keywordArr: [],
        keywords: '', //提交参数
        dataSource: '',
        rangePickerTime: [],
        //区域
        alarmArea: [],
        areaData2: [],
        areaData3: [],
        areaData4: [],
        //物品
        abnormalAccount: [],
        //账户
        communicationType: [],
        //网站
        num: '',
        //公用
        abnormalAccountRelease: '',
        dayQ: '',
        dayH: '',
      },
      rangePickerTime: [],
      indeterminateState: false,
      dictOptions: getDictItemsFromCache('dataSource'), //数据来源-字典值
      validatorRules: {
        name: [{ required: true, message: '请输入告警任务!' }],
        alarmArea: [{ required: true, message: '请选择告警区域!' }],
        rangePickerTime: [{ required: true, message: '请选择告警时间范围!' }],
        keywordArr: [{ required: true, message: '请选择关键词!' }],
        dataSource: [{ required: true, message: '请选择数据来源!', trigger: 'change' }],
      },
      selectedKeys: [1],
      areaData1: [],
      areaData2: [],
      areaData3: [],
      areaData4: [],
      keywordData: [],
      specificArea: [],
      isAdd: true,
    }
  },

  created() {
    this.getArea()
    this.KeywordQueryAll()
    if (this.category != undefined) {
      this.selectedKeys = [parseInt(this.category)] //编辑的情况，菜单选中对应项
    }
    //编辑
    if (this.id != undefined) {
      this.isAdd = false
      if (this.category == 1) this.getQyDetail()
      if (this.category == 2) this.getWpDetail()
      if (this.category == 3) this.getZhDetail()
      if (this.category == 4) this.getWzDetail()
    }
  },
  computed: {
    checkAllState() {
      let bool = false
      let dataSource =
        Object.keys(this.formData).length > 0 && this.formData.dataSource ? this.formData.dataSource.split(',') : []
      if (this.dictOptions.length === dataSource.length) {
        bool = true
      }
      return bool
    },
  },
  methods: {
    KeywordQueryAll() {
      alarmApi.KeywordQueryAll().then((res) => {
        if (res.success) {
          this.keywordData = res.result
        }
      })
    },
    getArea() {
      //市县
      alarmApi.smuAreaList({ category: '1' }).then((res) => {
        if (res.success) {
          this.areaData1 = res.result.smuAreaList
        }
      })
      //机场
      alarmApi.smuAreaList({ category: '2' }).then((res) => {
        if (res.success) {
          this.areaData2 = res.result.smuAreaList
        }
      })
      //火车站
      alarmApi.smuAreaList({ category: '3' }).then((res) => {
        if (res.success) {
          this.areaData3 = res.result.smuAreaList
        }
      })
      //港口
      alarmApi.smuAreaList({ category: '4' }).then((res) => {
        if (res.success) {
          this.areaData4 = res.result.smuAreaList
        }
      })
    },
    getQyDetail() {
      alarmApi
        .queryByIdQy({ id: this.id })
        .then((res) => {
          if (res.success) {
            this.formData.name = res.result.name
            this.formData.alarmArea = res.result.alarmArea.split(',')
            this.formData.areaData2 = res.result.specificArea[0].specificAreaOne.split(',')
            this.formData.areaData3 = res.result.specificArea[1].specificAreaOne.split(',')
            this.formData.areaData4 = res.result.specificArea[2].specificAreaOne.split(',')
            this.formData.keywordArr = res.result.keywords.split(',')
            this.formData.dataSource = res.result.dataSource
            this.formData.rangePickerTime = [res.result.warnBeginAt, res.result.warnEndAt]
            this.formData.warnBeginAt = res.result.warnBeginAt
            this.formData.warnEndAt = res.result.warnEndAt
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    getWpDetail() {
      alarmApi
        .queryByIdWp({ id: this.id })
        .then((res) => {
          if (res.success) {
            //目标人
            let listArr = res.result.smuggledGoods
            if (listArr != null && listArr.length > 0) {
              let arr2 = []
              listArr.forEach((item) => {
                arr2.push({ taskName: item.smuggledGoodsOne })
              })
              this.$refs.targetListId.setData(arr2)
            }
            this.formData.name = res.result.name
            this.formData.abnormalAccountRelease = res.result.abnormalAccountRelease
            //标签
            let labelArr = res.result.abnormalAccount
            if (labelArr != null && labelArr.length > 0) {
              let arr1 = []
              labelArr.forEach((item) => {
                arr1.push(item.abnormalAccountOne)
              })
              this.$refs.addLabelId2.setLabel(arr1)
            }
            this.formData.dayQ = res.result.dayQ
            this.formData.dayH = res.result.dayH
            this.formData.keywordArr = res.result.keywords.split(',')
            this.formData.dataSource = res.result.dataSource
            this.formData.rangePickerTime = [res.result.warnBeginAt, res.result.warnEndAt]
            this.formData.warnBeginAt = res.result.warnBeginAt
            this.formData.warnEndAt = res.result.warnEndAt
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    getZhDetail() {
      alarmApi
        .queryByIdZh({ id: this.id })
        .then((res) => {
          if (res.success) {
            this.formData.name = res.result.name
            this.formData.abnormalAccountRelease = res.result.abnormalAccountRelease
            //标签
            let labelArr = res.result.communicationType
            if (labelArr != null && labelArr.length > 0) {
              let arr1 = []
              labelArr.forEach((item) => {
                arr1.push(item.communicationTypeOne)
              })
              this.$refs.addLabelId1.setLabel(arr1)
            }
            //目标人
            let listArr = res.result.account
            if (listArr != null && listArr.length > 0) {
              let arr2 = []
              listArr.forEach((item) => {
                arr2.push({ taskName: item.accountOne })
              })
              this.$refs.targetListId.setData(arr2)
            }
            this.formData.dayQ = res.result.dayQ
            this.formData.dayH = res.result.dayH
            this.formData.keywordArr = res.result.keywords.split(',')
            this.formData.dataSource = res.result.dataSource
            this.formData.rangePickerTime = [res.result.warnBeginAt, res.result.warnEndAt]
            this.formData.warnBeginAt = res.result.warnBeginAt
            this.formData.warnEndAt = res.result.warnEndAt
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    getWzDetail() {
      alarmApi
        .queryByIdWz({ id: this.id })
        .then((res) => {
          if (res.success) {
            //目标人
            let listArr = res.result.webSite
            if (listArr != null && listArr.length > 0) {
              let arr2 = []
              listArr.forEach((item) => {
                arr2.push({ taskName: item.webSiteOne })
              })
              this.$refs.targetListId.setData(arr2)
            }
            this.formData.name = res.result.name
            this.formData.rangePickerTime = [res.result.warnBeginAt, res.result.warnEndAt]
            this.formData.warnBeginAt = res.result.warnBeginAt
            this.formData.warnEndAt = res.result.warnEndAt
            this.formData.keywordArr = res.result.keywords.split(',')
            this.formData.num = res.result.num
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    onImportData(arr) {
      // let arr1 = []
      // arr.forEach((item) => {
      //   arr1.push(item.abnormalAccount)
      // })
      this.$refs.addLabelId2.setImportData(arr)
      // arr.forEach((item) => {
      //   this.pageData.records.unshift({ taskName: item })
      //   this.isEdit.unshift(true)
      // })
      // this.pageData.records.forEach((item, index) => {
      //   item.id = index
      // })
    },
    onSelect(e) {
      //列表有无数据
      let recordLength
      if (this.$refs.targetListId != undefined) {
        recordLength = this.$refs.targetListId.getRecordLength()
      }
      // console.log('recordLength:' + recordLength)
      //表单有无填写
      let formDataFlag = false
      for (let key in this.formData) {
        if (this.formData[key] != '') {
          formDataFlag = true
        }
      }
      if (formDataFlag || recordLength > 0) {
        let that = this
        this.$confirm({
          title: `填写内容还未保存，切换后会导致内容丢失，是否切换?`,
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk() {
            that.formData = {}
            that.changeForm(that, e)
          },
        })
      } else {
        this.changeForm(this, e)
      }
    },
    changeForm(_this, e) {
      _this.category = e.key
      _this.selectedKeys = [_this.category]
      if (_this.category != 1) {
        setTimeout(() => {
          _this.$refs.targetListId.onClearRowKeys()
          _this.$refs.targetListId.setType(e.key)
          if (_this.$refs.addLabelId1 != undefined) {
            _this.$refs.addLabelId1.clearLabel()
          }
          if (_this.$refs.addLabelId2 != undefined) {
            _this.$refs.addLabelId2.clearLabel()
          }
        }, 100)
      }
    },
    onInportYCZH() {
      this.$refs.importModalId.add(2)
    },
    // 预警时间
    rangePickerChange(date) {
      this.$set(this.formData, 'warnBeginAt', date[0])
      this.$set(this.formData, 'warnEndAt', date[1])
    },
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.formData.id = this.id
          if (this.category == 1) this.qySubmit()
          if (this.category == 2) this.wpSubmit()
          if (this.category == 3) this.zhSubmit()
          if (this.category == 4) this.wzSubmit()
        }
      })
    },
    qySubmit() {
      let yqNum = this.formData.areaData2.length + this.formData.areaData3.length + this.formData.areaData4.length
      if (yqNum > 10) {
        this.$message.warning('特定区域数量不能超过10个！')
        return
      }
      this.formData.alarmArea = this.formData.alarmArea.join(',') //改成字符串
      this.$set(this.specificArea, 0, { num: 1, specificAreaOne: this.formData.areaData2.join(',') })
      this.$set(this.specificArea, 1, { num: 2, specificAreaOne: this.formData.areaData3.join(',') })
      this.$set(this.specificArea, 2, { num: 3, specificAreaOne: this.formData.areaData4.join(',') })
      this.formData.specificArea = this.specificArea
      if (this.formData.keywordArr.length > 0) {
        if (this.formData.keywordArr.length > 20) {
          this.$message.warning('最多可以选择20个关键词！')
          return
        }
        this.formData.keywords = this.formData.keywordArr.join(',') //数组转换成字符串
      }
      alarmApi
        .addQy(this.formData)
        .then((res) => {
          // 成功回调
          if (res.code == 200) {
            this.$router.push('/smuggleAlarm/alarmConfiguration')
          }
          this.$message.success("提交成功！")
        })
        .catch((res) => {
          // 失败回调
          this.$message.error(res.message)
        })
    },
    wpSubmit() {
      if (this.formData.alarmArea.length > 0) {
        this.formData.alarmArea = this.formData.alarmArea.join(',') //不需要也要改成字符串
      } else {
        this.formData.alarmArea = ''
      }
      //走私物品名称
      let listArr = this.$refs.targetListId.getData()
      // console.log(listArr)
      if (listArr.length <= 0) {
        this.$message.warning('走私物品不能为空！')
        return
      }
      let arr1 = []
      listArr.forEach((item, index) => {
        arr1.push({
          num: index + 1,
          smuggledGoodsOne: item.taskName,
        })
      })
      this.formData.smuggledGoods = arr1
      //异常账户
      let labelArr = this.$refs.addLabelId2.getLabel()
      // console.log("labelArr")
      // console.log(labelArr)
      let arr2 = []
      labelArr.forEach((item, index) => {
        arr2.push({
          num: index + 1,
          abnormalAccountOne: item,
        })
      })

      this.formData.abnormalAccount = arr2
      // console.log("aaaa")
      // console.log(this.formData.keywordArr)
      if (this.formData.keywordArr.length > 0) {
        if (this.formData.keywordArr.length > 20) {
          this.$message.warning('最多可以选择20个关键词！')
          return
        }
        this.formData.keywords = this.formData.keywordArr.join(',') //数组转换成字符串
      }
      // console.log("bbbb")
      alarmApi
        .addWp(this.formData)
        .then((res) => {
          // 成功回调
          if (res.code == 200) {
            this.$router.push('/smuggleAlarm/alarmConfiguration')
          }
          this.$message.success("提交成功！")
        })
        .catch((res) => {
          // 失败回调
          this.$message.error(res.message)
        })
    },
    zhSubmit() {
      if (this.formData.alarmArea.length > 0) {
        this.formData.alarmArea = this.formData.alarmArea.join(',') //不需要也要改成字符串
      } else {
        this.formData.alarmArea = ''
      }
      //账户名
      let listArr = this.$refs.targetListId.getData()
      if (listArr.length <= 0) {
        this.$message.warning('账户名不能为空！')
        return
      }
      let arr1 = []
      listArr.forEach((item, index) => {
        arr1.push({
          num: index + 1,
          accountOne: item.taskName,
        })
      })
      this.formData.account = arr1
      //通信方式
      let labelArr = this.$refs.addLabelId1.getLabel()
      let arr2 = []
      labelArr.forEach((item, index) => {
        arr2.push({
          num: index + 1,
          communicationTypeOne: item,
        })
      })
      this.formData.communicationType = arr2
      if (this.formData.keywordArr.length > 0) {
        if (this.formData.keywordArr.length > 20) {
          this.$message.warning('最多可以选择20个关键词！')
          return
        }
        this.formData.keywords = this.formData.keywordArr.join(',') //数组转换成字符串
      }
      alarmApi
        .addZh(this.formData)
        .then((res) => {
          // 成功回调
          if (res.code == 200) {
            this.$router.push('/smuggleAlarm/alarmConfiguration')
          }
          this.$message.success("提交成功！")
        })
        .catch((res) => {
          // 失败回调
          this.$message.error(res.message)
        })
    },
    wzSubmit() {
      if (this.formData.alarmArea.length > 0) {
        this.formData.alarmArea = this.formData.alarmArea.join(',') //不需要也要改成字符串
      } else {
        this.formData.alarmArea = ''
      }

      //监测网站
      let listArr = this.$refs.targetListId.getData()
      let arr1 = []
      listArr.forEach((item, index) => {
        arr1.push({
          num: index + 1,
          webSiteOne: item.taskName,
        })
      })
      this.formData.webSite = arr1
      if (this.formData.keywordArr.length > 0) {
        if (this.formData.keywordArr.length > 20) {
          this.$message.warning('最多可以选择20个关键词！')
          return
        }
        this.formData.keywords = this.formData.keywordArr.join(',') //数组转换成字符串
      }
      alarmApi
        .addWz(this.formData)
        .then((res) => {
          // 成功回调
          if (res.code == 200) {
            this.$router.push('/smuggleAlarm/alarmConfiguration')
          }
          this.$message.success("提交成功！")
        })
        .catch((res) => {
          // 失败回调
          this.$message.error(res.message)
        })
    },
    onBack() {
      this.$router.push('/smuggleAlarm/alarmConfiguration')
    },
    onCheckAllChange(e) {
      Object.assign(this, { indeterminateState: false })
      this.$set(
        this.formData,
        'dataSource',
        e.target.checked
          ? this.dictOptions
              .map((v) => {
                return v.value
              })
              .join(',')
          : null
      )
      console.log(this.formData.dataSource)
    },
    onChange(checkedList) {
      let dataLists = checkedList.split(',')
      this.indeterminateState = !!dataLists.length && dataLists.length < this.dictOptions.length
      this.$refs.ruleForm.validateField('dataSource') //主动校验dataSource
    },
  },
}
</script>
<style scoped lang="less">
.con-content {
  position: relative;
  .toolTip {
    position: absolute;
    right: -4%;
    top: 22%;
    z-index: 10;
  }
  .txfs /deep/ .ant-col-12 {
    width: 50%;
    .selectBox {
      width: 18%;
      float: left;
      margin-top: 4px;
      // display: inline-block;
    }
    .labelBox {
      width: 80%;
      display: inline-block;
      margin-left: 2%;
    }
  }
  .yczh /deep/ .ant-col-12 {
    width: 50%;
    .labelBox {
      width: 100%;
      display: inline-block;
    }
    .zjBtn {
      margin-left: 1%;
      position: absolute;
      .tp {
        position: absolute;
        right: 0;
        top: 15px;
      }
    }
  }
  .fbsj /deep/ .ant-col-12 {
    width: 87%;
  }
}
.tdqy /deep/ .ant-select {
  // float: left;
  display: inline-block;
  width: 32%;
  position: relative;
}
/deep/.ant-col-12 {
  // margin-left: 1%;
}

.container {
  padding-bottom: 15px !important;
}
.header-top {
  // height: 570px;
  padding: 24px;
  p {
    font-size: 16px;
    span {
      color: red;
    }
  }
}
</style>
